<template>
  <div class="fileBox">
    <div class="nav_left">
      <span class="tree_top" ref="treeTop"></span>
      <el-tree
        ref="tree"
        :data="treeData"
        node-key="id"
        :default-expanded-keys="expandedKeys"
        @node-click="nodeClick"
        style="padding: 10px 0">
            <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="treeContent">{{ node.label }}</span>
            <span class="treeEdit" >
               <el-button type="text" size="mini" @click="() => append(data)">
                <i class="el-icon-circle-plus"></i>
              </el-button>
              <el-button type="text" size="mini" @click="() => editEvent(data)">
                <i class="el-icon-edit"></i>
              </el-button>
              <el-button type="text" size="mini" @click="() => remove(node, data)">
                <i class="el-icon-delete"></i>
              </el-button>
            </span>
          </span>
      </el-tree>
      <el-dialog
        title=""
        :visible.sync="dialogVisible"
        width="30%"
        :modal-append-to-body='false'
        :before-close="handleClose">
        <div style="height: 40px;">
          <span style="float: left;width: 20%;line-height: 40px;text-align: center;font-size: 18px">{{titleName}}:</span>
          <el-input style="float:left;width: 70%;line-height: 40px" v-model="name"></el-input>
        </div>
        <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="SureEvent">确 定</el-button>
         </span>
      </el-dialog>
    </div>
    <div class="content_right">
        <div class="right_top">
          <div style="float: left;padding:10px 0 0 10px"><span>{{titles}}</span></div>
          <div style="float: right;padding-right: 60px;">
            <el-button style="" size="small" type="primary" @click="guideSelect()">+添加{{titles}}</el-button>
          </div>
        </div>

        <div class="tab-buy">
          <td-draggable element="el-table" ref='tdDragTable' :list="guideTableData" :data="guideTableData"
                        dragSelector="tbody" @end='guideEndDrag' style="width: 100%" :row-key="guideRowKeys"
                        :expand-row-keys="guideExpandRows" @expand-change="guideToggleRowExpansion">
            <!--:default-expand-all="true" @row-dblclick="guideToggleRowExpansion">-->
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table :data="props.row.fileList" style="width: 100% ; font-size: 12px" :border="true" stripe
                          v-if="fileListVisible">
                  <el-table-column type="index" label="序号" sortable width="80"></el-table-column>
                  <el-table-column prop="fileName" label="文件名" sortable width="280"
                                   :formatter="fileNameFormat"></el-table-column>
                  <el-table-column prop="uploadTime" :formatter="$utils.dateFormat" label="提交时间"></el-table-column>
                  <el-table-column prop="comment" :formatter="commentFormat" label="文件类型"></el-table-column>
                  <el-table-column label="操作" width="300" fixed="right">
                    <template slot-scope="scope">
                      <el-button @click="previewPDF(scope.row)" size="mini" plain>查看</el-button>
                      <el-button @click="guideUpload(scope.row)" size="mini" plain>更新</el-button>
                      <el-button @click="$utils.downloadFile(scope.row)" size="mini" plain>下载</el-button>
                      <el-button @click="deleteFile(scope.row)" size="mini" type="danger" plain>删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <br/>
                <!--:data="props.row.docList"-->
                <el-table :data="props.row.textList" style="width: 100% ; font-size: 12px" :border="true" stripe
                          v-if="richTextVisible">
                  <el-table-column type="index" label="序号" sortable width="80"></el-table-column>
                  <el-table-column prop="fileName" label="文件名" sortable width="280" :formatter="FwbFormat">
                  </el-table-column>
                  <el-table-column prop="uploadTime" :formatter="$utils.dateFormat" label="提交时间"></el-table-column>
                  <el-table-column prop="comment" :formatter="commentFormat" label="文件类型"></el-table-column>
                  <el-table-column label="操作" width="220" fixed="right">
                    <template slot-scope="scope">
                      <el-button @click="fwbView(scope.row)" size="mini" plain>查看</el-button>
                      <el-button @click="fwbEdit(scope.row)" size="mini" plain>编辑</el-button>
                      <el-button @click="deleteFile(scope.row)" size="mini" type="danger" plain>删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="sortId" sortable label="序号" width="80"></el-table-column>
            <el-table-column align="center" prop="id" sortable label="ID" width="80"></el-table-column>
            <el-table-column align="center" prop="title" sortable label="标题"></el-table-column>
            <el-table-column align="center" prop="fileList" :formatter="fileListFormat" sortable label="文件数"
                             width="80"></el-table-column>
            <!--<el-table-column align="center" prop="tabType" sortable label="栏目类型"></el-table-column>-->
            <el-table-column align="center" sortable width="240" label="操作">
              <template slot-scope="scope">
                <el-button @click="guideEdit(scope.row)" size="mini" plain>编辑</el-button>
                <el-button @click="guideDel(scope.row,scope.$index)" size="mini" type="danger" plain>删除</el-button>
              </template>
            </el-table-column>
          </td-draggable>
        </div>
        <el-dialog :title="'添加'+(titles)" :visible.sync="guideAddDialogVisible" width="35%" :before-close="guideDialogClose"
                   :modal-append-to-body='false'>
          <el-form :model="guideForm" :rules="guideFormRules" ref="guideForm" label-width="130px">
            <el-form-item label="编号" prop="id">
              <el-input v-model="guideForm.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="guideForm.title"></el-input>
            </el-form-item>
            <el-form-item label="类型">
              <el-checkbox-group v-model="docType">
                <el-checkbox label="1" :disabled="check1">中文PDF</el-checkbox>
                <el-checkbox label="2" :disabled="check2">英文PDF</el-checkbox>
                <el-checkbox label="3" :disabled="check3">富文本</el-checkbox>
                <el-checkbox label="4" :disabled="check4">下载文档</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="guideDialogClose" plain>取消</el-button>
        <el-button type="primary" @click="guideFormSubmit">确 定</el-button>
      </span>
        </el-dialog>

        <el-dialog title="上传文件" :append-to-body="true" :visible.sync="fileDialogVisible" :before-close="handleClose"
                   width="70%">
          <file-uploader v-if="fileDialogVisible" :file-info="fileInfo"></file-uploader>
        </el-dialog>
        <el-dialog :append-to-body="true" :visible.sync="fwbVisible" :before-close="handleCloseFwb" width="75%">
          <RichtextVue v-if="fwbVisible" @closeEvent="closeDialog"></RichtextVue>
        </el-dialog>

      </div>
  </div>
</template>

<script>
  import {http} from '../../../assets/commonjs/axios';
  import RichtextVue from '../../common/RichTextURP';
  import FileUploader from '../../../components/common/FileUploader';
  import {Copy, delArrayObject} from '../../../assets/commonjs/utils';
  import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn'


  export default {
    data() {
      return {
        titleName:"文件名称",
        name:'',
        expandedKeys:[25],
        boolonNum:1,
        expandedid:'',
        saveData:[],
        treeData:[],
        fileObj:[],
        dialogVisible: false,
        titles: '政府投资工程建设项目',
        fwbVisible: false,
        richTextVisible: false,
        fileListVisible: false,
        id: null,
        fdaId: 0,
        dragOptions: {
          draggable: '.el-table__row'
        },
        fileDialogVisible: false,
        guideType: '1',
        check1: false,
        check2: false,
        check3: false,
        check4: false,
        fileInfo: {
          fileId: 0, //原文件ID，更新文件时传原文件的fileId，新上传文件传0
          bizId: 1, // id
          bizType: 2,
          catalogId: 70101,
          userAccount: 'admin',
          projectNo: 'public',//项目报建申请表ID
        },
//=====================================================================================================
        guideListDialogVisible: false,
        guideAddDialogVisible: false,
        guideListData: [],//办事指南清单
        guideTableData: [],//办事指南表格
        docType: [],
        guideForm: {
          sortId: "",
          id: "",
          title: "",
          tabType: "25",//
        },
        guideFormRules: {
          tabType: [
            {required: true, message: '必填', trigger: 'blur'},
          ],
        },
        guideExpandRows: [],//要展开的行，数值的元素是row的key值
//=====================================================================================================





      };
    },
    created(){
      this.getTree()
      this.queryFileList()
    },
    methods: {
      nodeClick(data,checked,node){
        let booler = true;
        this.expandedid = data.id;
        if(data.id != 25){
          this.$refs.treeTop.style.zIndex = "-1"
        }
            this.titles = data.label;
            this.guideForm.tabType = data.id
            this.queryFileList()
        //=========================== 在获取tree数据时保持之前点击树的形态不变 ================================
        for(let i = 0; i<this.expandedKeys.length;i++){
          if(this.expandedKeys[i] == data.id){
                booler = false;
          }
        }
        if(booler){
          this.expandedKeys.push(data.id)
        }else{
          for(let i = 0; i<this.expandedKeys.length;i++){
            if(this.expandedKeys[i] == data.id){
              this.expandedKeys.splice(i,1)
            }
          }
        }
        //===============================  end   ===================================================
      },

      append(data) {
        this.titleName = "文件名称"
        this.name = '';
        this.dialogVisible = true;
        this.saveData =data;
      },
      editEvent(data){
        this.titleName = "重命名"
        this.name = data.label;
        this.dialogVisible = true;
        this.saveData =data;
      },

      //删除树节点事件
      remove(node, data) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          http('post','directory/delete_indexDirectory',{
            id: data.id,
          }).then(require=>{
            let res = require.data;
            if(res.success){
              this.getTree()
              this.$message({message: res.message, type: 'success'});
            }else{
              this.$message({message: res.message, type: 'warning'});
            }
          })
        }).catch(err => {
        })
      },

      //保存或编辑时弹出层的确定事件
      SureEvent(){
        if(this.titleName == "文件名称"){
          this.saveOrEdit(0,this.saveData.id)
        }else if(this.titleName == "重命名"){
          this.saveOrEdit(this.saveData.id,this.saveData.parentId)
        }
        this.dialogVisible = false;
      },

      //保存编辑API
      saveOrEdit(id,parentId){
        http('post','directory/save_indexDirectory',{
          directory: {
            id: id,
            title: this.name,
            parentId:parentId
          }
        }).then(require=>{
          let res = require.data;
          if(res.success){
            this.getTree()
            this.boolonNum ++;
            this.$message({message: res.message, type: 'success'});
          }else{
            this.$message({message: res.message, type: 'warning'});
          }
        })
      },

      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },

      //获取树数据  // console.log(this.$refs.tree.data);
      getTree(){
        http('post','directory/get_indexDirectoryList',{
          "parentId": 0
        }).then(res=>{
          this.treeData = this.getJsonTree(res.data.result,1)
        })
      },

      //递归方法 生成 json tree 数据
      getJsonTree(data, parentId) {
        let itemArr = [];
        for (let i = 0; i < data.length; i++) {
          let node = data[i];
          if (node.parentId == parentId) {
            let newNode = {};
            newNode.id = node.id;
            newNode.parentId = node.parentId;
            newNode.label = node.title;
            itemArr.push(newNode);
            newNode.children = this.getJsonTree(data, node.id);
            if (newNode.children.length === 0) {
              delete newNode.children;
            }
          }

        }
        return itemArr;
      },

      //富文本编辑事件
      fwbEdit(row) {
        this.fwbVisible = true;
        sessionStorage.fdaId = row.fdaId;
        sessionStorage.itId = row.itId;
        sessionStorage.itEdit = 1;
      },
      //富文本查看事件
      fwbView(row) {
        this.fwbVisible = true;
        sessionStorage.fdaId = row.fdaId;
        sessionStorage.itId = row.itId;
        sessionStorage.itEdit = 0;
      },
      //=====================================================================================================
      //删除办事指南接口
      guideDelAPI(id, callback) {
        http("post", "directory/delete_fileDirectory", {
          id: id
        }).then(function (res) {
          callback(res.data);
        }).catch(err => {
          console.log("err", err);
        })
      },
      //保存办事指南接口
      guideSaveAPI(data, callback) {
        http("post", "directory/save_fileDirectory", {
          docType: this.docType,
          directory: data,
        }).then(function (res) {
          callback(res.data);
        }).catch(err => {
          console.log("err", err);
        })
      },
      //点击添加按钮选择或新建单体
      guideSelect() {
        this.check1 = false;
        this.check2 = false;
        this.check3 = false;
        this.check4 = false;
        this.docType = [];
        this.guideAddDialogVisible = true;
        this.guideForm.id = 0;
      },
      //选中办事指南加入办事指南列表
      guideAddToList(rowdata) {
        new Copy(rowdata, "submitdata");//提交数据
        this.guideSaveAPI(submitdata, res => {
          if (res.success) {
            let repeatId = delArrayObject(this.guideTableData, "id", submitdata.id, submitdata);
            if (repeatId == -1) {
              this.guideTableData.push(res.result);
            }
            if (this.guideListData.length > 0) {
              delArrayObject(this.guideListData, "id", submitdata.id);
            }
            this.$message({message: res.message, type: 'success'});
            this.queryFileList();
          } else {
            this.$message({message: res.message, type: 'warning'});
          }
        });
      },
      //提交办事指南表单
      guideFormSubmit() {
        this.$refs.guideForm.validate((valid) => {
          if (valid) {
            this.guideAddToList(this.guideForm);
            this.$refs.guideForm.resetFields();
            this.guideAddDialogVisible = false;
            this.queryFileList();
          }
        });
      },
      //取消或者关闭表单
      guideDialogClose() {
        this.$refs.guideForm.resetFields();
        this.guideAddDialogVisible = false;
      },
      //编辑办事指南表单
      guideEdit(rowdata) {
        this.docType = rowdata.docTypeList;
        this.check1 = false;
        this.check2 = false;
        this.check3 = false;
        this.check4 = false;
        rowdata.docTypeList.forEach((item) => {
          if (item == 1) {
            this.check1 = true;
          } else if (item == 2) {
            this.check2 = true;
          } else if (item == 3) {
            this.check3 = true;
          } else if (item == 4) {
            this.check4 = true;
          }
        });
        new Copy(rowdata, "newdata");
        this.guideForm = newdata;
        this.guideAddDialogVisible = true;
      },
      //删除办事指南
      guideDel(rowdata, index) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (rowdata.id) {
            this.guideDelAPI(rowdata.id, res => {
              if (res.success) {
                this.guideTableData.splice(index, 1);
                this.$message({message: res.message, type: 'success'});
              } else {
                this.$message({message: res.message, type: 'warning'});
              }
            });
          } else {
            this.guideTableData.splice(index, 1);
          }
        }).catch(() => {
        });
      },
      guideUpload(row) {
        this.fileInfo.fileId = row.id || 0;
        this.fileInfo.bizId = row.fdaId;
        this.fileInfo.designNo = row.fdId;
        this.fileDialogVisible = true;
        this.guideToggleRowExpansion(row)
      },
      fileNameFormat(row) {
        let data = row.fileName;
        return data == null ? '待上传' : row.fileName;
      },
      FwbFormat(row) {
        let data = row.content;
        if (data) {
          if (data.length > 10) {
            data = data.substring(0, 10) + "......"
          }
        }
        return data == null ? '待上传' : data;
      },
      commentFormat(row) {
        let data = row.docType;
        if (!data || data === undefined) {
          return "";
        } else {
          if (data == 4) {
            return '下载文档';
          } else if (data == 3) {
            return '富文本';
          } else {
            return data == 1 ? '中文文档' : '英文文档';
          }
        }
      },
      fileListFormat(row, column) {
        let data = row[column.property];
        if (!data || data === undefined) {
          return 0;
        }
        return data.length;
      },
      //=====================================================================================================
      //删除事件
      deleteFile(row) {
        let _this = this;
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          http("post", "directory/delete_fileDirectoryAssociated", {
            id: row.fdaId
          }).then(function (res) {
            if (res.data.success) {
              _this.$message({message: res.data.message, type: 'success'});
              _this.queryFileList();
            }
          }).catch(err => {
            console.log("err", err);
          })

        }).catch(() => {
        });
      },
      handleClose(done) {
        this.queryFileList();
        done();
      },
      handleCloseFwb(done) {
        done();
      },
      closeDialog() {
        this.fwbVisible = false;
        this.queryFileList();
      },
      queryFileList() {
        http('post', "directory/get_fileDirectoryList", {
          tabType: this.guideForm.tabType,
        }).then(res => {
          let data = res.data;
          if (data.message) {
            this.guideTableData = data.result || [];
          }
        }).catch(err => {
          console.log("err", err);
        })
      },
      // 获取row的key值
      guideRowKeys(row) {
        return row.id;
      },
      guideToggleRowExpansion(row, expandedRows) {
        if (row.id === this.guideExpandRows[0]) {
          this.guideExpandRows = [];
        } else {
          this.guideExpandRows = [];
          this.guideExpandRows.push(row.id);
        }
        this.fileListVisible = row.fileList.length == 0 ? false : true;
        this.richTextVisible = row.textList.length == 0 ? false : true;
      },
      guideEndDrag(event) {
        let fromId = event.newIndex;
        let oldId = event.oldIndex;
        let toId = fromId;
        if (fromId > oldId) {
          toId = fromId - 1;
        } else {
          toId = fromId + 1;
        }
        if (toId !== fromId) {
          http("post", "directory/update_directorySort", {
            id: this.guideTableData[fromId].id,
            // tabType: this.guideForm.tabType,
            newSortId: this.guideTableData[toId].id,
            // oldSortId: event.oldIndex + 1,
          }).then(res => {
            res = res.data;
            if (res.success) {
              this.$message({message: res.message, type: 'success'});
            } else {
              this.$message({message: res.message, type: 'warning'});
            }
          }).catch(err => {
            console.log("err", err);
          })
        }
      },
    },
    watch:{
      boolonNum(oldval,newval) {
        let boolers = true
        for(let i = 0; i<this.expandedKeys.length;i++){
          if(this.expandedKeys[i] == this.expandedid){
            boolers = false;
          }
        }
        if(boolers){
          this.expandedKeys.push(this.expandedid)
        }
      }
    },
    components:{
      FileUploader,
      RichtextVue
    }
  };
</script>
<style scoped>
  .fileBox{
    height: 90%;
    width: 100%;
  }
  .tree_top{
    width: 100%;
    height: 26px;
    background: rgba(154, 176, 212, 0.4);
    color: red;
    position: absolute;
    top: 36px;
    z-index: 100;
  }

  .nav_left{
    height: 100%;
    background: white;
    width: 330px;
    float: left;
    position: relative;
  }
  .treeContent{
    display: inline-block;
  }

  .nav_left>>>.el-tree-node:focus>.el-tree-node__content, .el-tree-node__content:hover{
    background: rgba(154, 176, 212, 0.4);
  }
  .nav_left>>>div.el-tree-node__content:hover span.treeEdit{
    display: inline-block;
  }
  .treeEdit {
    display: none;
    padding-left:30px;
  }
  .content_right{
    height: calc(100% - 40px);
    float: right;
    width: calc(100% - 350px);
    overflow: auto;
    position: relative;
    padding-top: 40px;
  }
  .right_top{
    color: #000;
    position: fixed;
    top: 70px;
    right: 25px;
    width: calc(100% - 645px);
    z-index: 100;
    background: white;
    padding-bottom:10px;
  }

</style>
